const fileReader = require('../fileReader')
const execSync = require('child_process').execSync

const baseDir = '/home/note/'

function dateFormat (date) {
    function fill (num) {
        return num >= 10 ? num : '0' + num
    }

    return date.getFullYear() + '-' + fill(date.getMonth() + 1) + '-' + fill(date.getDate())
}

function lastModify (file) {
    let cmd = 'cd ' + baseDir + '; git log --pretty=format:"%ad" --date=format:"%Y-%m-%d %T" -1 ' + file.path
    return execSync(cmd).toString().trim()
}

function getNoteList () {
    let files = fileReader.read(baseDir)

    files = files.filter(file => file.name.endsWith('.md'))

    let list = []
    for (let file of files) {
        let folder = file.path.substring(baseDir.length)
        let name = file.name.substring(0, file.name.length - 3)
        folder = folder.substring(0, folder.length - file.name.length)
        if (folder.length > 0 && folder.endsWith('/')) {
            folder = folder.substring(0, folder.length - 1)
        }
        list.push({
            name: name,
            date: lastModify(file),
            folder: folder.length ? folder : null,
            title: (folder.length ? folder + ' / ' : '') + name
        })
    }

    list.sort(function (a, b) {
        return (new Date(a.date)).getTime() - (new Date(b.date)).getTime()
    })

    return list
}

module.exports = function (request, response) {
    response.writeHead(200, {'Content-Type': 'application/json'})
    response.write(JSON.stringify(getNoteList()))
    response.end()
}
